package org.yanex.util;

import android.os.Message;

public abstract class ThreadHelper {
	
	private boolean interrupted = false;
	
	private Thread thr = new Thread() {
		public void run() {
			Boolean result = task();
			if (this.isInterrupted()) {
				interrupt();
				return;
			}
			if (result)
				handler.sendMessage(handler.obtainMessage());
			else
				errorHandler.sendMessage(errorHandler.obtainMessage());
		}
	};
	final android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if (!interrupted)
        		finalizator();
        	else
        		interrupted();
        }
	};
	final android.os.Handler errorHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if (!interrupted)
        		error();
        	else
        		interrupted();
        }
	};
	
	public void interrupt() {
		if (thr!=null && thr.isAlive()) {
			interrupted=true;
			thr.interrupt();
			interrupted=false;
		}
	}
	
	public void start() {
		starter();
		thr.start();
	}
	
	public void start(int priority) {
		starter();
		thr.setPriority(priority);
		thr.start();
	}
	
	public void interrupted() {}
	public void starter() {}
	public void error() {}
	
	public abstract boolean task();
	public abstract void finalizator();
}
